import {
  storeBindingsBehavior
} from 'mobx-miniprogram-bindings'
import {
  getCouponShelfList,
  receiveBizCouponNew
} from "@src/api/coupon";
// import { debounce } from '@src/common/coupon'
import {
  getCouponDetailNew
} from '@src/api/member';
import $color from "@src/common/color";
import dayjs from "dayjs";
import pageHandleUtil from "@src/common/pageHandleUtil";
import base from "@src/store/base";
import router from "@src/router";
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['businessName', 'businessLogo', 'themeColor', 'themeTitleColor']
  }],
  properties: {

  },
  data: {
    activeTab: 0,
    couponTypeArray: [{
      name: '全部',
      id: 0
    }, {
      name: '代金券',
      id: 1
    }, {
      name: '折扣券',
      id: 2
    }, {
      name: '兑换券',
      id: 3
    }],
    couponList: [],
    //展示再页面上的列表
    showList: [],
    //当前点击的券
    id: null,
    //当前点击领取券的code
    code: null,
    ifloading: false,
  },
  methods: {
    onLoad(option) {


    },
    onShow() { },
    onHide() {

    },
    onUnload() {

    },
    async onPullDownRefresh() {
      await this.getCouponShelfListFunc();
      wx.stopPullDownRefresh();
      // setTimeout(() => {

      // }, 1000)
    },
    getCouponShelfListFunc() {
      this.setData({
        loading: true
      })
      getCouponShelfList().then(res => {
        if (res.code == 0) {
          // 过滤过期的券
          console.log('获取优惠券', res.data)
          let eachLis = res.data
          let couponList = []
          eachLis.forEach(el => {
            // 最新时间戳
            let timestamp = Date.parse(new Date());
            let newTime = timestamp / 1000
            // 过期时间戳
            // let date = new Date(el.endTime)
            let endTime = ''
            wx.getSystemInfo({
              success: result => {
                if (result.system.indexOf('iOS') != -1) {
                  const date = el.endTime + " 23:59:59"
                  const dt = new Date(date.replace(/-/g, "/"))
                  endTime = dt.getTime() / 1000
                  // console.log('ios - endTime', endTime)
                } else {
                  let date = new Date(el.endTime + " 23:59:59")
                  endTime = date.getTime() / 1000
                  // console.log('安卓endTime---', endTime)
                }
              }
            });
            // console.log(el.couponName + ':' + (endTime - newTime))
            if (endTime > newTime) {
              couponList.push(el)
            }
          });
          this.setData({
            couponList: couponList,
            // activeTab: 0
          });
          this.handleShakeCoupon();
          this.setData({
            showList: this.data.couponList,
          })
          this.handleIfGetCoupon()
          this.filterCouponFunc()
        }
        this.setData({
          loading: false
        })
      }).catch(error => {
        this.setData({
          loading: false
        })
      })
    },
    handleShakeCoupon() {
      let couponList = this.data.couponList;
      couponList.forEach(item => {
        item.isClick = false;
        item.ifloading = false;
      });
      this.setData({
        couponList
      })
    },
    handleIfGetCoupon() {
      let couponList = this.data.couponList;
      couponList.forEach(item => {
        item.getCoupon = false
      })
      this.setData({
        couponList,
        showList: couponList
      })
    },
    handleCoupon(e) {
      console.log('e', e);
      let id = e.currentTarget.dataset.id;
      if (id != this.data.activeTab) {
        this.setData({
          activeTab: id
        });
        this.filterCouponFunc()
      }
    },
    filterCouponFunc() {
      let couponList = this.data.couponList;
      let activeTab = this.data.activeTab;
      let showList = [];
      couponList.forEach(item => {
        //全部
        if (activeTab === 0) {
          showList.push(item)
        }
        //代金券
        else if (activeTab === 1) {
          if (item.couponType == 'cash' || item.couponType == 'cash_wx_busi' || item.couponType == 'cash_wx_pay') {
            showList.push(item)
          }
        }
        //折扣券
        else if (activeTab === 2) {
          if (item.couponType == 'discount' || item.couponType == 'discount_wx_busi') {
            showList.push(item)
          }
        }
        //兑换券
        else if (activeTab === 3) {
          if (item.couponType == 'exchange') {
            showList.push(item)
          }
        }

      })
      this.setData({
        showList
      })
      console.log('activeTab--', this.data.activeTab)
      console.log('调filterCouponFunc--', this.data.showList)
    },
    //立即领取
    nowGetCoupon(e) {
      console.log('e', e);
      let getCoupon = e.currentTarget.dataset.item.getCoupon;
      let receiveCode = e.currentTarget.dataset.item.receiveCode;
      let id = e.currentTarget.dataset.item.id;
      let couponList = this.data.couponList;
      let showList = this.data.showList;
      let prototype = e.currentTarget.dataset.item;
      const self = this;
      let flag = true;
      let nowIndex = 0;
      this.setData({
        id
      });
      if (getCoupon) { } else {
        showList.forEach((item, index) => {
          if (item.id == id) {
            nowIndex = index
          }
        })
        let temp = 'showList[' + nowIndex + '].ifloading'
        this.setData({
          [temp]: true
        })
        receiveBizCouponNew(receiveCode).then(res => {
          if (res.code == 0) {
            let params = res.data.params;
            let codes = res.data.codes;
            console.log('params', params)
            if (codes) {
              self.setData({
                code: codes[0]
              })
            }
            if (res.data.finish) {
              wx.showToast({
                title: '领取成功',
                icon: 'success',
                duration: 2000
              })
              let couponArr = self.IfGetUtil(couponList, id);
              let showArr = self.IfGetUtil(showList, id);
              if (codes) {
                couponArr = self.setCodeFunc(couponList, codes[0], id);
                showArr = self.setCodeFunc(showList, codes[0], id);
              }
              self.setData({
                couponList: couponArr,
                showList: showArr,
                [temp]: false
              });
            } else {
              let temp = 'showList[' + nowIndex + '].ifloading'
              this.setData({
                [temp]: false
              })
              self.showReceiveCoupon(prototype, params, codes)
            }
          }
        }).catch(error => {
          self.setData({
            [temp]: false
          });
        })
      }

    },
    a() {
      // let getCoupon = e.currentTarget.dataset.item.getCoupon;
      // let receiveCode = e.currentTarget.dataset.item.receiveCode;
      // let id = e.currentTarget.dataset.item.id;
      // let couponList = this.data.couponList;
      // let showList = this.data.showList;
      // let prototype = e.currentTarget.dataset.item;
      // const self = this;
      // let flag = true;
      // let nowIndex = 0;
      // this.setData({ id })
      // if (getCoupon) {
      // } else {
      //     receiveBizCouponNew(receiveCode).then(res => {
      //       console.log("执行")
      //       if (res.code == 0) {
      //         let params = res.data.params;
      //         let codes = res.data.codes;
      //         console.log('params', params)
      //         if (codes) { self.setData({ code: codes[0] }) }
      //         if (res.data.finish) {
      //           wx.showToast({
      //             title: '领取成功',
      //             icon: 'success',
      //             duration: 2000
      //           })
      //           let couponArr = self.IfGetUtil(couponList, id);
      //           let showArr = self.IfGetUtil(showList, id);
      //           if (codes) {
      //             couponArr = self.setCodeFunc(couponList, codes[0]);
      //             showArr = self.setCodeFunc(showList, codes[0]);
      //           }
      //           self.setData({ couponList: couponArr, showList: showArr });
      //         } else {
      //           self.showReceiveCoupon(prototype, params, codes)
      //         }
      //       }
      //     })  
      // }
    },
    //监听微信商家券是否领取成功
    getNowFunc() {
      // let couponList = this.data.couponList;
      // let showList = this.data.showList;
      const self = this;
      let id = this.data.id;
      let code = this.data.code;
      let couponList = self.IfGetUtil(this.data.couponList, id);
      let showList = self.IfGetUtil(this.data.showList, id);
      couponList = self.setCodeFunc(couponList, code);
      showList = self.setCodeFunc(showList, code);
      this.setData({
        couponList,
        showList
      });
      console.log('showList', showList)
    },
    //立即使用
    nowUseCoupon(e) {
      console.log('e', e);
      let code = e.currentTarget.dataset.item.code;
      // return;
      if (code) {
        router.push({
          name: 'member/couponDetailNew',
          params: {
            type: 1,
            model: 1,
            couponCode: code
          }
        })
      }
    },
    //工具函数,遍历 设置是否领取
    IfGetUtil(arr, id) {
      arr.forEach(item => {
        if (item.id === id) {
          item.getCoupon = true
        }
      })
      return arr
    },
    //工具函数，设置code值
    setCodeFunc(arr, code, id) {
      arr.forEach(item => {
        if (item.id === id) {
          item.code = code
        }
      })
      return arr;
    },
    //展示领取弹框
    showReceiveCoupon(prototype, params, codes) {
      this.selectComponent("#receiveCoupon").dialogShow(prototype, params, codes);
    },
    onLogin() {
      this.getCouponShelfListFunc()
    },
  }
})